package com.study.thymeleaf.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Mono;

/**
 * webclient工具类 ]
 * 
 */
public class WebClientUtil {

    /**
     * 发送post请求
     * @param uri
     * @param data
     * @param header
     * @return
     */
    public static String sendPostByJson(String uri, Object data, Map<String,Object> header){
        //构建webclient
        WebClient.Builder builder = WebClient.builder();
        builder.baseUrl(uri);
        //设置头部信息
        if(header != null && !header.isEmpty()){
            Set<Map.Entry<String, Object>> set = header.entrySet();
            for(Map.Entry<String, Object> m : set){
                builder.defaultHeader(m.getKey(), m.getValue().toString());
            }
        }
        //创建client
        WebClient client = builder.build();
        Mono<String> mono = client.post()
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(data))
                .retrieve().bodyToMono(String.class);
        return mono.block();
    }

    /**
     * 发送参数在URL中的post请求
     * @param uri
     * @param params
     * @return
     */
    public static String sendPost(String uri, String params){
        //创建client
        Mono<String> mono = WebClient.create().post()
                .uri(uri + "?" + params)
                .retrieve().bodyToMono(String.class);
        return mono.block();
    }

    /**
     * 发送get请求
     * @param uri
     * @param data
     * @param header
     * @return
     */
    public static String sendGet(String uri, String data, Map<String,Object> header){
        //拼接uri字符串
        if(data != null && !data.isEmpty()){
            uri = uri+"?"+data;
        }
        //构建webclient
        WebClient.Builder builder = WebClient.builder();
        builder.baseUrl(uri);
        //设置头部信息
        if(header != null && !header.isEmpty()){
            Set<Map.Entry<String, Object>> set = header.entrySet();
            for(Map.Entry<String, Object> m : set){
                builder.defaultHeader(m.getKey(), m.getValue().toString());

            }
        }
        //创建client
        WebClient client = builder.build();
        //发送请求，并获取响应
        Mono<String> mono = client.get().retrieve().bodyToMono(String.class);
        return mono.block();
    }
}